package com.opensource.lzx.ssh;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.opensource.lzx.entity.ServerConfigEntity;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @Author: 739891618@qq.com
 * @Date: 2022-11-13 15:43:24
 * @ClassName: RestartSupport
 * @Describe: this is a ...
 */
public class RestartSupport {

    public static void restart(ServerConfigEntity entity) {
        if (Objects.isNull(entity)) {
            System.out.println("Windows os can not support restart.....");
            return;
        }
        System.out.println("Host:" + entity.getHost() + " send to restart command.");
        Connection connection = doGetConnection(entity);

        doExecCommand(connection, entity.getExecCommand());
    }

    private static void doExecCommand(Connection connection, String execCommand) {
        try {
            Session session = connection.openSession();

            session.execCommand(execCommand, StandardCharsets.UTF_8.name());

            handlerResponse(session.getStdout(), StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void handlerResponse(InputStream in, String charsetName) throws Exception {
        InputStream inputStream = new StreamGobbler(in);

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charsetName));
        StringBuilder buffer = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        System.out.println("执行返回结果：" + buffer.toString());
    }

    private static Connection doGetConnection(ServerConfigEntity entity) {
        Connection connection = new Connection(entity.getHost(), Integer.parseInt(entity.getPort()));
        try {
            connection.connect();

            boolean isConnect = connection.authenticateWithPassword(entity.getSshUserName(), entity.getSshPassword());
            if (isConnect) {
                System.out.println("服务器连接成功...");
            } else {
                System.out.println("服务器连接失败...");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return connection;
    }
}
